<template>
  <ViewLayout
    ref="layout"
    :configs="configs"
    :config-tree-props="configTreeProps"
    @saveTreeFormSuccess="saveTreeFormSuccess"
    @formSaveSuccess="formSaveSuccess"
  >
    <template #leftTreeAppendBzCode>
      <el-button
        size="mini"
        @click="handleSortItems"
      >
        调整菜单顺序
      </el-button>
      <BKModal
        v-model="sortModalVisible"
        width="600"
        height="90%"
        title="调整菜单顺序"
      >
        <SortItems
          :data="sortItemData"
          :check-folder-method="checkFolderMethod"
          :icon-method="iconMethod"
          :on-draggable-move="onDraggableMove"
          @refresh="sortItemData=$event"
          @save="handleConfirmSort"
        />
      </BKModal>
      <BKModal
        v-model="permissionModalVisible"
        width="600"
        title="初始化菜单权限"
      >
        <div
          class="full-height p-a-mini"
          style="padding-bottom: 0;"
        >
          <BKForm
            :items="permissionItems"
            :rules="permissionRules"
            @submit="handleSubmitPermission"
          />
        </div>
      </BKModal>
      <ConfigForm
        ref="form"
        :configs="formConfigs"
        :before-submit="beforeSubmit"
        @saveSuccess="saveSuccess"
      />
    </template>
    <!-- <template #gridToolbarLeftAppend="{treeNode}">
      <el-button
        :disabled="!treeNode"
        size="mini"
        @click="initPermission(treeNode)"
      >
        初始化菜单权限
      </el-button>
    </template> -->
    <template #gridToolbarLeftAppend>
      <div
        style="display: inline-block;"
        class="f-16 m-l-mini"
      >
        <span>应用:</span><span class=" m-h-mini c-blue f-w">{{ yy }}</span>个
        <span class="m-l-mini">模块:</span><span class=" m-h-mini c-blue f-w">{{ mk }}</span>个
        <span class="m-l-mini">操作权限:</span><span class=" m-h-mini c-blue f-w">{{ czqx }}</span>个
      </div>
    </template>
  </ViewLayout>
</template>

<script>
import request from '@/utils/request'
import getAppId from '../getAppId'

const appId = 'YSJC'
const bzCode = 'YSJC'

export default {
  name: 'Menu',
  components: {
    SortItems: () => import('../../../../../../../bk-web-foundation/src/views/skeleton/components/sort-items.vue'),
    ViewLayout: () => import('../../../../../../../bk-web-foundation/src/views/skeleton/components/view-layout.vue')
  },
  data () {
    return {
      configs: {
        customNodeClickHandler: this.handleNodeClick,
        tree: {
          canSwitchBzCode: false,
          appId,
          bzCode,
          treeConfigId: 'YSJC_QXGL_CDGL',
          menuConfig: [
            { title: '新增菜单', visible: (data) => data.att2 !== 'C', handler: 'addManagementNode' },
            { title: '编辑菜单', visible: true, handler: 'editManagementNode' },
            { title: '删除菜单', visible: data => data.isLeaf, handler: 'removeManagementNode' }
          ],
          management: {
            modal: {
              width: 400
            },
            module: '菜单',
            metaSet: 'YSQJC_PW_MENU',
            parentNodeProps: { PARENT_ID: 'id', APP_ID: 'att5' },
            primaryKeyProps: { MENU_ID: 'id' },
            formItemProcessor: this.formItemProcessor
          },
          renderContent: this.renderContent,
          customAddTopTreeNode: this.customAddTopTreeNode,
          defaultExpandAll: false
        },
        grid: {
          checkGridParent: this.checkGridParent,
          afterFormLoading: this.afterFormLoading,
          modal: {
            width: 400
          },
          module: '按钮',
          appId,
          bzCode,
          metaSet: 'YSQJC_PW_MENU',
          parentNodeProps: { PARENT_ID: 'id', APP_ID: 'att5' }
        }
      },
      sortModalVisible: false,
      sortItemData: [],
      permissionModalVisible: false,
      permissionItems: [
        { type: 'input', label: '权限码前缀', field: 'PERMS' },
        { type: 'input', label: '权限码描述', field: 'PERMS_NAME' }
      ],
      permissionRules: {
        PERMS: [{ required: true, message: '权限码前缀不能为空' }],
        PERMS_NAME: [{ required: true, message: '权限码描述不能为空' }]
      },
      configTreeProps: {},
      yy: 0,
      mk: 0,
      czqx: 0
    }
  },
  computed: {
    formConfigs () {
      return Object.assign({ appId, bzCode }, this.configs.tree.management, { formItemProcessor: this.topFormItemProcessor })
    }
  },
  created () {
    this.appId = getAppId()
    this.configTreeProps = {
      treeQueryParams: { APPID: this.appId, bzCode: 'YSJC' }
    }
    this.getStatistics()
  },
  methods: {
    renderContent (h, { node, data, store }) {
      return (
        <div class="custom-tree-node d-flex ai-c">
          {
            <span class="p-l-s node-icon f-14">
              {
                <i class={'icon ' + (data.att2 === 'C' ? 'el-icon-menu' : 'el-icon-folder')}/>
              }
              <span>{ node.label }</span>
            </span>
          }
        </div>
      )
    },
    handleNodeClick (node) {
      this.$refs.layout.refreshGrid(true, node.att2 === 'M')
    },
    checkGridParent (parent) {
      return parent.att2 === 'C'
    },
    afterFormLoading (formComponent) {
      formComponent.form.MENU_TYPE = 'F'
      formComponent.allItems.find(i => i.field === 'MENU_TYPE').props.disabled = true
    },
    initPermission (treeNode) {
      this.currentNode = treeNode
      this.permissionModalVisible = true
    },
    async handleSubmitPermission (form) {
      await request.post('/ysjc/user/initButton', {
        MENU_ID: this.currentNode.id,
        ...form,
        APP_ID: this.appId
      })
      this.$message.success('操作成功！')
      this.permissionModalVisible = false
      this.$refs.layout.refreshGrid()
    },
    checkFolderMethod (item) {
      return item.att2 === 'M'
    },
    iconMethod (item) {
      return item.att2 === 'C' ? 'el-icon-menu' : 'el-icon-folder'
    },
    onDraggableMove (data) {
      if (data.draggedContext.element.fid === data.relatedContext.element.fid) {
        return true
      }
      if (data.draggedContext.element.att2 === 'C') {
        // 拖拽菜单
        if (data.relatedContext.element) {
          // 改变顺序
          return data.relatedContext.element.att2 === 'C'
        } else {
          return true
        }
      } else {
        // 拖拽目录
        if (data.relatedContext.element) {
          return data.relatedContext.element.att2 === 'M'
        } else {
          return true
        }
      }
    },
    handleSortItems () {
      const treeData = this.$refs.layout.$refs.tree.treeData
      this.sortItemData = this.$utils.deepClone(treeData)
      this.sortModalVisible = true
    },
    async handleConfirmSort () {
      const list = []
      this.recursiveHandleItem(this.sortItemData, list, 'ROOT')
      await request.post('/SingleTable/curd', {
        appId,
        bzCode,
        metaSet: 'YSQJC_PW_MENU',
        methodCode: 'batch',
        methodParams: JSON.stringify({
          batchParam: list.map(r => {
            return {
              MENU_ID: r.id,
              PARENT_ID: r.fid,
              MENU_ORD: r.order
            }
          })
        })
      })
      this.$message.success('操作成功！')
      this.sortModalVisible = false
      this.$refs.layout.refreshTree()
    },
    recursiveHandleItem (source, target, fid) {
      let index = 1
      for (const item of source) {
        item.fid = fid
        item.order = index
        target.push(item)
        index++
        if (item.children) {
          this.recursiveHandleItem(item.children, target, item.id)
        }
      }
    },
    async formItemProcessor ({ items, rules }) {
      const item = items.find(item => item.field === 'MENU_TYPE')
      if (item) {
        const mock = await this.$utils.dictionary.getOptionsByKey(item.props.dictionaryKey)
        const index = mock.findIndex(m => m.value === 'F')
        const list = mock.slice(0)
        list.splice(index, 1)
        item.props.mock = list
      }
      return { items, rules }
    },
    customAddTopTreeNode () {
      this.$refs.form.show({ MENU_TYPE: 'M', PARENT_ID: 'ROOT' }, false)
    },
    topFormItemProcessor ({ items, rules }) {
      const item = items.find(item => item.field === 'MENU_TYPE')
      if (item) {
        item.props.disabled = true
      }
      return { items, rules }
    },
    beforeSubmit (form) {
      const data = {
        appId: this.formConfigs.appId,
        bzCode: this.formConfigs.bzCode,
        metaSet: this.formConfigs.metaSet,
        methodCode: 'insert',
        methodParams: JSON.stringify(form)
      }
      return data
    },
    saveSuccess (e, formData) {
      this.$refs.layout.$refs.tree.refreshAllNodes()
      this.saveTreeFormSuccess(formData)
    },
    saveTreeFormSuccess (formData) {
      if (formData.resData.keys?.MENU_ID) {
        this.$request.post('/ysjc/user/initMenuEncrypt', { MENU_ID: formData.resData.keys?.MENU_ID })
      }
    },
    formSaveSuccess (e, formData) {
      this.saveTreeFormSuccess(formData)
    },
    async getStatistics () {
      const { rows } = await this.$request.singleTableOperation({
        url: '/grid/getTableData',
        metaSet: 'YSQJC_PW_MENU',
        methodCode: 'selectCalysjcYsjcYsqjcPwMenuTotalList',
        methodParams: {}
      })
      this.yy = 0
      this.mk = 0
      this.czqx = 0
      for (const row of rows) {
        if (row.MENU_TYPE === 'M') {
          this.yy = row.SUM
        }
        if (row.MENU_TYPE === 'F') {
          this.czqx = row.SUM
        }
        if (row.MENU_TYPE === 'C') {
          this.mk = row.SUM
        }
      }
    }
  }
}
</script>
